#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Daemon.hpp"
#include <memory>
#include <signal.h>

static void Usage(const std::string& proc)
{
    std::cout << "\nUsage: " << proc << " Port" << std::endl;
}

static Response CalculatorHelper(const Request &req)
{
    Response resp(0, 0, req._x, req._y, req._op);
    switch (req._op)
    {
    case '+':
        resp._ret = req._x + req._y;
        break;
    case '-':
        resp._ret = req._x - req._y;
        break;
    case '*':
        resp._ret = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resp._code = 1;
        else
            resp._ret = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resp._code = 2;
        else
            resp._ret = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void Calculator(int sock)
{
    std::string inbuffer;
    while(true)
    {
        bool ret = Recv(sock, &inbuffer);
        if(!ret) break;
        // 读取成功
        std::string package = Decode(inbuffer);
        if(package.empty()) continue;
        // 保证该报文是一个完整的报文
        logMessage(NORMAL, "%s", package.c_str());
        Request req;
        // 反序列化:字节流 -> 结构化
        req.Deserialize(package);
        // 业务逻辑
        Response resp = CalculatorHelper(req);
        // 序列化
        std::string respStr = resp.Serialize();
        // 添加报头,形成一个完整的报文
        respStr = Encode(respStr);
        Send(sock, respStr);
    }
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    MyDaemon(); // 进程守护进程化

    std::unique_ptr<TcpServer> ptr(new TcpServer(atoi(argv[1])));
    ptr->BindService(Calculator);
    ptr->Start();

    return 0;
}